package com.maishi.programmer.jainzhioffer;

import java.util.ArrayList;

/**
 * Created by brossdong on 2018/3/30.
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字，例如，如果输入如下矩阵：
 * 1 2 3 4
 * 5 6 7 8
 * 9 10 11 12
 * 13 14 15 16
 * 则依次打印出数字
 * 1  2   3  4
 * 8  12 16 15
 * 14 13 9  5
 * 6  7  11 10.
 */
public class TestProblem29 {

    public ArrayList<Integer> printMatrix(int [][] matrix) {
        //定义空的数组
        ArrayList list = new ArrayList();
        /*//如果为多维矩阵
        //从左到右打印
        for (int i = 0;i <= matrix[0].length - 1;i++) {
            list.add(matrix[i]);
        }
        //从上到下打印
        for (int i = 1;i <= matrix.length - 1;i++) {
            list.add(matrix[i]);
        }
        //从右往左打印
        for (int i = matrix.length - 1;i <= matrix[0].length - 1;i++) {
            list.add(matrix[i]);
        }
        //从下往上打印
        for (int i = matrix[0][matrix.length-1];i <= matrix.length - 2;i++) {
            list.add(matrix[i]);
        }
        return list;*/
        int left=0,right=matrix[0].length-1,top=0,boom= matrix.length-1;//记录四个角的位置
        while ((right > left) && (boom > top)) {
            //从左到右 -----ok
            for (int i = left;i <= right;i++) {
                list.add(matrix[top][i]);
            }
            //从上到下
            for (int i = top + 1;i <= boom;i++) {
                list.add(matrix[i][right]);
            }
            //从右到左
            for(int i = right - 1;i >= left;i--){
                list.add(matrix[boom][i]);
            }
            //下到上
            for (int i = boom - 1;i > top;i--) {
                list.add(matrix[i][left]);
            }
            left++;
            right--;
            boom--;
            top++;
        }
        if((boom==top)&&(left<right)){//单独剩下一行的情况
            for(int i=left;i<=right;i++){
                list.add(matrix[top][i]);
            }
        }
        if((left==right)&&(boom>top)){//单独剩下一列的情况
            for(int i =top;i<= boom;i++){
                list.add(matrix[i][left]);
            }
        }
        if((boom==top)&&(right==left)){//单独剩下一个元素的情况
            list.add(matrix[left][boom]);
        }
        return list;
    }

    public static void main(String[]args){
        int[][] arr={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
        System.out.println(arr.length-1);
        System.out.println(arr[0].length-1);
        TestProblem29 test = new TestProblem29();
        System.out.println(test.printMatrix(arr));
    }

}
